package com.leo.tool.serialize.protobuf;

import java.nio.file.Files;
import java.nio.file.Paths;

import com.baidu.bjf.remoting.protobuf.Codec;
import com.baidu.bjf.remoting.protobuf.ProtobufProxy;
import com.baidu.bjf.remoting.protobuf.annotation.Protobuf;

import lombok.SneakyThrows;

/**
 * <li>仅{@link Protobuf}标记属性参与序列化（无视static，transient，父类属性）</li>
 * <li>反序列化时若无属性会自动设置默认值，{@link Enum}默认为ordinal为0的值</li>
 * <br/>
 * <li>https://github.com/jhunters/jprotobuf</li>
 * <br/>
 * @author Leo
 * @date 2019/07/08
 */
public class JprotobufSerializer<T> {

    private Codec<T> codec;

    public JprotobufSerializer(Class<T> clazz) {
        this.codec = ProtobufProxy.create(clazz);
    }

    @SneakyThrows
    public byte[] serialize(T t) {
        return codec.encode(t);
    }

    @SneakyThrows
    public void serialize(String path, T t) {
        Files.write(Paths.get(path), serialize(t));
    }

    @SneakyThrows
    public T deserialize(byte[] bytes) {
        return codec.decode(bytes);
    }

    @SneakyThrows
    public T deserialize(String path) {
        return deserialize(Files.readAllBytes(Paths.get(path)));
    }

}
